<template>
  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
    <el-table :data="vehiclesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="购车年份" align="center" prop="purchaseYear" width="180" />
      <el-table-column label="单位名称" align="center" prop="organizationName" />
      <el-table-column label="车辆状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车辆类型" align="center" prop="type" />
      <el-table-column label="座位数" align="center" prop="seatCount" />
      <el-table-column label="驾驶员" align="center" prop="driver" />
      <el-table-column label="图片" align="center" width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.image"
            fit="cover"
          />
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitSelection">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listVehicles, availableVehiclesList } from "@/api/vehicles/vehicles";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "SelectVehicleDialog",
  props: {
    open: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: "选择车辆",
      vehiclesList: [],
      selectedVehicles: []
    };
  },
  created() {
    this.getVehicles();
    this.getDicts();
  },
  methods: {
    getVehicles() {
      availableVehiclesList().then(response => {
        this.vehiclesList = response.rows.filter(vehicle => vehicle.status === 0);
      });
    },
    handleSelectionChange(selection) {
      this.selectedVehicles = selection;
    },
    submitSelection() {
      this.$emit("submit", this.selectedVehicles);
      this.$emit("update:open", false);
    },
    cancel() {
      this.$emit("update:open", false);
    },
    // 根据状态值获取对应的文字描述
    getStatusText(status) {
      const statusItem = this.delVehiclesStatus.find(item => item.dictSort === status);
      return statusItem ? statusItem.dictLabel : "未知状态";
    },
    /** 根据词典查找车辆品牌 */
    getDicts() {
      getDicts('vehicle_status').then(response => {
        this.delVehiclesStatus = response.data;
      });
    },
  }
};
</script>
